package com.olympus.hermes.product.service;

import com.olympus.hermes.common.service.AbstractService;
import com.olympus.hermes.product.bean.dto.category.CategoryTreeTypeDTO;
import com.olympus.hermes.product.bean.dto.category.CreateCategoryDTO;
import com.olympus.hermes.product.bean.dto.category.UpdateCategoryDTO;
import com.olympus.hermes.product.domain.Category;
import com.olympus.hermes.product.repo.CategoryRepo;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author Mickey
 * @since 2021/1/12
 */
@Service
@AllArgsConstructor
public class CategoryService extends AbstractService {

    private final CategoryRepo categoryRepo;

    private final StringRedisTemplate redisTemplate;

    public void create(CreateCategoryDTO createCategory) {
        creatorFor(categoryRepo)
                .instance(createCategory::convertTo)
                .call();
    }

    public void update(UpdateCategoryDTO updateCategory) {
        updaterFor(categoryRepo)
                .id(updateCategory.getId())
                .call();
    }

    public void delete(Long id) {

    }

    public List<CategoryTreeTypeDTO> all() {
        List<Category> all = categoryRepo.findAll();
        Map<String, CategoryTreeTypeDTO> outputCategoryMap = all.stream()
                .map(category -> new CategoryTreeTypeDTO().reverse().convert(category))
                .collect(Collectors.toMap(CategoryTreeTypeDTO::getKey, Function.identity()));
        outputCategoryMap.forEach((id, outputCategory) -> {
            if (!outputCategory.getParentId().equals("0")) {
                CategoryTreeTypeDTO parentCategory = outputCategoryMap.get(outputCategory.getParentId());
                List<CategoryTreeTypeDTO> childCategories = parentCategory.getChildren();
                if (null == childCategories) {
                    ArrayList<CategoryTreeTypeDTO> newChildCategories = new ArrayList<>();
                    newChildCategories.add(outputCategory);
                    parentCategory.setChildren(newChildCategories);
                } else {
                    childCategories.add(outputCategory);
                }
            }
        });
        return outputCategoryMap
                .values()
                .stream()
                .filter(outputCategory -> outputCategory.getParentId().equals("0"))
                .collect(Collectors.toList());
    }


}
